package com.zyy.study.redisson.controller;

import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/getToken")
public class RedisSemaphoreController {
    private RSemaphore semaphore;

    @Autowired
    public void setRedissonClient(RSemaphore semaphore) {
        this.semaphore = semaphore;
    }

    @PostMapping("/tryAcquire/{id}")
    public void getSemaphoreToken(@PathVariable int id){
        if (semaphore.tryAcquire()) {
            System.out.println("用户"+id+"通过客户端1获取到资源");
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                System.out.println("用户"+id+"通过客户端1释放资源");
                semaphore.release();
            }
        }else {
            System.out.println("客户端1:当前资源不足，请稍后再试");
        }
    }
}
